// utils/websocket.js
import Vue from "vue";

class WebSocketClient {
  constructor(url) {
    this.url = url
    this.socket = null
    this.reconnectDelay = 5000 // 重连间隔 5s
    this.heartbeatTimer = null
    this.reconnectTimer = null
    this.userId = null
  }

  connect(userId) {
    this.userId = userId

    if (this.socket && this.socket.readyState === WebSocket.OPEN) {
      console.log("WebSocket 已连接，无需重复连接")
      return
    }

    this.socket = new WebSocket(this.url)

    this.socket.onopen = () => {
      console.log("✅ WebSocket 连接成功")
      this.send({type: "INIT", userId: this.userId}) // 首次连接发送 userId
    }

    this.socket.onmessage = (event) => {
      console.log("📩 收到消息:", event.data)

      // 1. 心跳处理
      if (event.data === "ping") {
        this.send("pong")
        return
      }

      // 2. 业务消息通知
      try {
        const msg = JSON.parse(event.data)  // 约定后端发送 JSON
        Vue.prototype.$notify({
          title: msg.title || "新消息",
          message: msg.content || JSON.stringify(msg),
          type: msg.type || "info",
          duration: 5000
        })
      } catch (e) {
        // 不是 JSON，当作普通字符串处理
        Vue.prototype.$notify({
          title: "新消息",
          message: event.data,
          type: "info",
          duration: 5000
        })
      }
    }


    this.socket.onclose = () => {
      console.log("⚠️ WebSocket 已关闭，准备重连")
      this.stopHeartbeat()
      this.reconnect()
    }

    this.socket.onerror = (err) => {
      console.error("❌ WebSocket 出错:", err)
      this.stopHeartbeat()
      this.reconnect()
    }
  }

  send(message) {
    if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
      console.warn("WebSocket 未连接，消息丢弃:", message)
      return
    }

    if (message === "pong") {
      this.socket.send(message)
    } else {
      this.socket.send(JSON.stringify(message))

    }

  }


  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  reconnect() {
    if (this.reconnectTimer) return
    this.reconnectTimer = setTimeout(() => {
      console.log("🔄 正在尝试重连 WebSocket...")
      this.connect(this.userId)
      this.reconnectTimer = null
    }, this.reconnectDelay)
  }

  close() {
    this.stopHeartbeat()
    if (this.socket) {
      this.socket.close()
      this.socket = null
    }
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    console.log("🚪 WebSocket 已关闭并清理")
  }
}

export default new WebSocketClient("ws://localhost:19204/ws")
